/*
    Copyright (c) 2014-2016 Pentair Technical Products, Inc.
    All rights reserved.
    Pentair Technical Products, Inc. proprietary and confidential.

    Description:
	This header file defines interfaces
	provided by the ipmb.c module.

    $Revision: 13636 $
*/
#ifndef __HAL_IPMB_H__
#define __HAL_IPMB_H__

#include <sys/ioctl.h>
#include <stdio.h>

#include "appdefs.h"
#include "ring.h"


#define IPMB_MIN_RETRY_TIME		60 /* ms, min interval before retry */

#define ipmb_init()	do { } while (0)
#define ipmb_buffer_attach(chan)		i2c_buffer_attach(chan)
#define ipmb_buffer_detach(chan)		i2c_buffer_detach(chan)
#define ipmb_set_addr(chan, addr1, addr2)	\
	i2c_set_addr(chan, addr1, addr2)
#define	ipmb_buffer_status(chan)		i2c_buffer_status(chan)


#if 0
static inline int ipmb_send(unsigned char chan, unsigned short addr,
	unsigned char * buf, int len)
{
    i2c_send(chan, addr | I2C_START | I2C_STOP, buf, len);
    return i2c_get_last_error(chan);
}
#endif

void print_recv_buf(unsigned char *buf, int len)
{
	printf("\n");
	int i;
	for(i =0; i < len; i++)
	{
		printf("%.2x ",buf[i]);
	}
	printf("\n");
}

static inline int ipmb_recv(ring_t * r, unsigned char *buf, int length)
{
    //ring_t * r = i2c_get_ring(chan);
    int cnt, len;

    /* disable interrupts */
    //save_flags_cli(flags);

    /* get amount of data in the ring */
    cnt = ring_data_size(r);
    //printf("ipmb_recv: cnt %d!\n",cnt);

    /* enable interrupts */
    //restore_flags(flags);
    //printf("ipmb_recv: truncate msg cnt %d!\n",cnt);

    if (cnt)
    {
    	/* get message length */
    	len = ring_get(r);
    	//printf("ipmb_recv: truncate msg cnt %d len %d!\n",cnt, len);

    	if (len > length)
    	{
    		printf("ipmb_recv: truncate msg!\n");
    		len = length;
    	}

    	if (!len || len > cnt)
    	{
    		/* corrupted ring data, discard all */
    		ring_clear(r);
    		//printf("corrupted ring data, discard all.\n");

    		//set ring tail to kernel ring
    		//ioctl(g_i2c_file, I2C_SET_RING, r);
    		len = 0;
    	}
    	else
    	{
    		ring_get_buf(r, buf, len);
    		//print_recv_buf(buf,len);

    		//set ring tail to kernel ring
    		//ioctl(g_i2c_file, I2C_SET_RING, r);
    	}
    }
    else
    {
    	len = 0;
    }

    return len;
}
#endif /* __HAL_IPMB_H__ */
